using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.IO;

namespace RevitForge.ViewModels
{
    public partial class ApiKeySetViewModel : ObservableObject
    {
        private string _apiKey;
        public string ApiKey
        {
            get => _apiKey;
            set => SetProperty(ref _apiKey, value);
        }

        public ICommand SaveCommand { get; }
        public ICommand CancelCommand { get; }
        public event EventHandler CloseRequested;
        public ApiKeySetViewModel()
        {
            try
            {
                string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string apiKeyPath = Path.Combine(appDataPath, "RevitForge", "apikey.config");

                if (File.Exists(apiKeyPath))
                {
                    ApiKey = File.ReadAllText(apiKeyPath);
                }
            }
            catch (Exception)
            {
                // 处理错误
            }

            SaveCommand = new RelayCommand(Save);
            CancelCommand = new RelayCommand(Cancel);
        }

        private void Save()
        {
            try
            {
                string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string settingsPath = Path.Combine(appDataPath, "RevitForge");
                string apiKeyPath = Path.Combine(settingsPath, "apikey.config");

                if (!Directory.Exists(settingsPath))
                {
                    Directory.CreateDirectory(settingsPath);
                }

                File.WriteAllText(apiKeyPath, ApiKey);
                CloseRequested?.Invoke(this, EventArgs.Empty);
            }
            catch (Exception)
            {
                // 处理错误
            }
        }

        private void Cancel()
        {
            CloseRequested?.Invoke(this, EventArgs.Empty);
        }
    }
}